<?php

namespace app\model;

use hsg\Hsg;
use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class PlateformCode extends Model
{
    public function codePage(): array
    {
        $param = request()->param();
        $data = $this->with(['gift' => function ($query) {
        }, 'plate'])->when(!empty($param['pid']), function ($query) use ($param) {
            $query->where("pid", "=", $param['pid']);
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->whereLike("mobile", "%{$param['mobile']}%");
        })->when(!empty($param['pack']), function ($query) use ($param) {
            $query->where("gid", "=", $param['pack']);
        })->when(!empty($param['state']), function ($query) use ($param) {
//            $query->where("state","=",$param['state'] == 3?5:$param['state']);
            if ($param['state'] == 3) $query->where("state", "=", 5);
            elseif ($param['state'] == 1) $query->where("state", "=", 1);
            elseif ($param['state'] == 4) $query->where("state", "=", 6);
            else $query->whereNotIn('state', [1, 5, 6]);
        })->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $param['pageSize'] ?? 30,
            "page" => $param['page'] ?? 1
        ])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function supplierChangeOrder(): array
    {
        $page = request()->param('page');
        $auth = getAuthorization();
        $data = $this->with(['gift' => function ($query) {
            $query->with(['productAttr' => function ($query) {
                $query->with(['product' => function ($query) {
                    $query->with(['productData'])->hidden(['create_time', 'update_time'])->order('attr,product');
                }])->field("id,pack,name,prices,sku,change_number");
            }]);
        }, 'plate' => function ($query) {
            $query->hidden(['password', 'encode']);
        }
        ])->where([
            ['pid', '=', $auth['id']],
            ['state', '>', 1]
        ])->order(['draw_time' => 'desc'])->paginate(['list_rows' => 30, 'page' => $page ?? 1])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total'],'last_page'=>$data['last_page']];
    }

    public function gift(): HasOne
    {
        return $this->hasOne(Package::class, "id", "gid");
    }

    public function plate(): HasOne
    {
        return $this->hasOne(Plateform::class, "id", "pid");
    }

    public function recodePage()
    {
        $param = request()->param();
        $data = $this->with(['gift', 'plate'])->whereNotIn("state", [1, 5, 6])->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $param['pageSize'] ?? 30,
            "page" => $param['page'] ?? 1
        ])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function addCode(): array
    {
        $param = request()->post();
        $data = [];
        for ($i = 0; $i < $param['number']; $i++) {
            $data[] = [
                'pid' => $param['pid'],
                'gid' => $param['gid'],
                'code' => Str::random(8, 1),
                'state' => 1,
                'last_time' => empty($param['last_time']) ? 0 : strtotime($param['last_time'] . "23:59:59")
            ];
        }
        $this->saveAll($data);
        return $data;
    }

    public function codeDetail(): array
    {
        $code = request()->param('code');
        $data = $this->with(['gift' => function ($query) {
            $query->with(['productAttr' => function ($query) {
                $query->with(['product' => function ($query) {
                    $query->with(['productData'])->hidden(['create_time', 'update_time'])->order('attr,product');
                }])->field("id,pack,name,prices,sku,change_number");
            }]);
        }, 'plate' => function ($query) {
            $query->hidden(['password', 'encode']);
        }])->where([['code', '=', $code]])->find();
        if (empty($data)) throw new \Exception("礼包不存在，请与服务商确认礼包信息！", 7001);
        if ($data['state'] == 6) throw new \Exception("礼包码已领取，请勿重复领取！", 7003);
        if (($data['last_time'] > 0 && $data['last_time'] < time() && $data['state'] == 1) || $data['state'] == 5) {
            $data->state = 5;
            $data->save();
            throw new \Exception("礼包码已过期，请与服务商确认礼包信息！", 7002);
        }
        $data = $data->toArray();
        $gift = $data['gift'];
        $gift['content'] = htmlspecialchars_decode($gift['content']);
        $plat = $data['plate'];
        $draw_status = $data['state'];
        return compact("gift", "plat", 'draw_status');
    }

    public function codeRecharge()
    {
        $data = request()->post();
        $code = $this->where(['code' => $data['code'], 'gid' => $data['pack']])->find();
        if (empty($code)) throw new \Exception("礼包码不存在，请重新输入！", 7001);
        if ($code->state != 1 || ($code->state == 1 && $code->last_time > 0 && $code->last_time < time()))
            throw new \Exception("礼包码已过期，请重新输入！", 7002);
        //处理礼包数据
        $this->startTrans();
        $order = array_map(function ($v) use ($code, $data) {
            return [
                'order_sn' => date("YmdHis") . Str::random(4, 1),
                'mobile' => $data['mobile'],
                'account' => $data['mobile'],
                'product' => $v['id'],
                'code' => $code->code,
                'supplier' => $code->pid,
                'gid' => $data['pack'],
                'attr' => $data['attr'],
                'price' => $v['money'],
                'number' => $v['number'],
                'state' => 2,
                'pay_time' => date("Y-m-d H:i:s"),
//                'update_time' => time(),
            ];
        }, $data['product']);
        $_ord = app(Order::class);
        $_ord->saveAll($order);
        $code->state = 4;
        $code->mobile = $data['mobile'];
        $code->save();
        $this->commit();
        //处理发货信息
        $prod = array_column($data['product'], 'number', 'id');
        $sn = array_column($order, 'order_sn', 'product');
        $product = app(Product::class)->where(['id' => array_column($data['product'], 'id')])->select();
        $productCode = app(ProductCode::class);
        foreach ($product as $v) {
            if ($v['type'] == 4) {
                $vals = $productCode->where(['pid' => $v['id'], 'state' => 1, 'is_del' => 1,])->limit($prod[$v['id']])->column("id");
                if ($vals == $prod[$v['id']]) {
                    $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 5]);//券码生成成功
                    $productCode->where(['id' => $vals])->update(['state' => 2, 'draw_time' => date("Y-m-d H:i:s")]);
                } else {
                    $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 6]);//券码生成失败
                }
            } else if ($v['type'] == 1) {
                $cod = explode("-", $v['bar_code']);
                if ($cod[0] == 'HSG') {
                    $hsg = new Hsg;
                    $createCoupon = $hsg->createFindCoupon($data['mobile'], end($code), $prod[$v['id']]);
                    if ($createCoupon['code'] != 0) {
                        $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 6]);
                    } else {
                        $its = $createCoupon['data'];
                        $url = $hsg->createUrl($data['mobile']);
                        $its['url'] = $url;
                        $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 5, 'order_info' => json_encode($its, 320)]);//发券成功
                    }
                }
            } else if ($v['type'] == 3) {
                $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 5, 'order_info' => json_encode(['url' => $v['user_text']])]);//发券成功
            } else {
                $_ord->where(['order_sn' => $sn[$v['id']]])->update(['state' => 5]);//发券成功
            }
        }
        return $code;
    }

    public function destroyCode(): array
    {
        $id = request()->post("id");
        $data = $this->findOrFail($id);
        $data->state = 6;
        $data->save();
        return $data->toArray();
    }

    public function static(): array
    {
        $auth = getAuthorization();
        //获取当前渠道的渠道码
        $gid = $this->where(['pid' => $auth['id']])->group('gid')->column('gid');
//        dd($gid);
        $pack = Package::whereIn('id', $gid)->column('id,name');
//        dd($pack);
        $data = $this->whereIn('gid', $gid)->where(['pid' => $auth['id']])->field('state,count(id) as num,gid')->group('state,gid')->select()->toArray();
//        dd($data);
        $pack = array_column($pack, null, "id");
        $its = [
            ['name' => '未领取', 'number' => 0, 'state' => 1],
            ['name' => '已领取', 'number' => 0, 'state' => 2],
            ['name' => '已使用', 'number' => 0, 'state' => 4],
            ['name' => '已过期', 'number' => 0, 'state' => 5],
            ['name' => '已作废', 'number' => 0, 'state' => 6],
        ];
        foreach ($pack as $k => &$v) {
            $v['data'] = $its;
            foreach ($data as $vv) {
//                if ($vv['state'] == 3) $vv['state'] = 2;
                $kk = $vv['state'] - 1;
                if ($vv['state'] == 3) $kk = 1;
                if ($vv['state'] > 3) $kk = $vv['state'] - 2;
                if ($vv['gid'] == $k) {
                    $v['data'][$kk]['number'] += $vv['num'];
                }
            }
        }
        return array_values($pack);
    }
}
